package com.sgcc.pda.mdrh.task.safe.service;

import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.RemoteException;

import com.google.gson.Gson;
import com.sgcc.pda.baselibrary.utils.LogUtil;
import com.sgcc.pda.hzaidl.IHZAidlCallback;
import com.sgcc.pda.hzaidl.api.InterfaceFactory;
import com.sgcc.pda.hzaidl.entity.CommonErrorBean;
import com.sgcc.pda.hzaidl.entity.RequestBean;
import com.sgcc.pda.hzaidl.entity.ResponseBean;
import com.sgcc.pda.hzaidl.error.HZErrorCode;
import com.sgcc.pda.mdrh.task.safe.router.SafeRouter;
import com.sgcc.pda.mdrh.task.safelibrary.BuildConfig;
import com.sgcc.pda.mdrh.zoom.router.BaseOperateRouter;
import com.sgcc.pda.mdrh.zoom.router.BasicRouter;
import com.sgcc.pda.mdrh.zoom.router.BusinessRouter;
import com.sgcc.pda.mdrh.zoom.router.GisRouter;
import com.sgcc.pda.mdrh.zoom.router.SsalRouter;
import com.sgcc.pda.mdrh.zoom.router.WebRouter;
import com.sgcc.pda.safe.SafeAidlCallback;
import com.sgcc.pda.zoom.HardwareBinderUtil;

/**
 * Created by jianiuqi on 2020/09/17.
 */
public class SafeRouterService extends SafeService {

    @Override
    public String post(String data, final SafeAidlCallback callback) {
        try {
            LogUtil.e("safeControl收到数据：", data);
            final RequestBean requestBean = new Gson().fromJson(data, RequestBean.class);
            String mainCode = requestBean.getMainCode();
            //hardware请求透明转发即可
            if (mainCode.equals("hardware")) {
                //TODO 请求需要调用平台服务
                return HardwareBinderUtil.getInstance().post(data, new IHZAidlCallback() {
                    @Override
                    public void callback(String s) throws RemoteException {

                    }

                    @Override
                    public IBinder asBinder() {
                        return null;
                    }
                });
            }

            String methodName = requestBean.getMethodName();
            //方法名校验
            InterfaceFactory.InterfaceBean interfaceBean = InterfaceFactory.getInterface(methodName);

            if (interfaceBean == null) {
                callbackFail(callback, HZErrorCode.ERROR_1005, methodName);
                return fail(HZErrorCode.ERROR_1005, methodName);
            }

            //获取router并校验
            BaseOperateRouter router = getRouter(mainCode);
            if (router == null) {
                callbackFail(callback, HZErrorCode.ERROR_1002, requestBean.getTag());
                return fail(HZErrorCode.ERROR_1002, requestBean.getTag());
            }

            if (interfaceBean.isAsync()) {
                //异步返回
                router.handleResult(this, requestBean, new BaseOperateRouter.CompleteListener() {
                    @Override
                    public void complete(int retCode, String result) {
                        switch (retCode) {
                            case 0:
                                // 失败回调
                                callbackFail(callback, result, requestBean.getTag());
                                break;
                            case 1:
                                // 成功回调
                                callbackSuccess(result, callback, requestBean.getTag());
                                break;
                            case 2:
                                // 进度回调
                                callbackProgress(result, callback, requestBean.getTag());
                                break;
                        }
                    }
                });
            } else {
                //需要同步结果
                String result = router.handleResult(this, requestBean, new BaseOperateRouter.CompleteListener() {
                    @Override
                    public void complete(int retCode, String result) {
                        switch (retCode) {
                            case 0:
                                // 失败回调
                                callbackFail(callback, result, requestBean.getTag());
                                break;
                            case 1:
                                // 成功回调
                                callbackSuccess(result, callback, requestBean.getTag());
                                break;
                            case 2:
                                // 进度回调
                                callbackProgress(result, callback, requestBean.getTag());
                                break;
                        }
                    }
                });
                return result == null ? fail(HZErrorCode.ERROR_1000, requestBean.getTag()) : success(result, requestBean.getTag());
            }

        } catch (Exception e) {
            e.printStackTrace();
            RequestBean requestBean = new Gson().fromJson(data, RequestBean.class);
            callbackFail(callback, HZErrorCode.ERROR_1000, e.getMessage(), requestBean.getTag());
            return fail(HZErrorCode.ERROR_1000, e.getMessage(), requestBean.getTag());
        }
        return null;
    }


    /**
     * 根据mainCode获取对应的router。
     */
    private BaseOperateRouter getRouter(String mainCode) {
        BaseOperateRouter router = null;
        switch (mainCode) {
            case "web":
                router = BuildConfig.ISSSAL ? new SsalRouter() : new WebRouter();
                break;
            case "basic":
                router = new BasicRouter();
                break;
            case "gis":
                router = new GisRouter();
                break;
            case "business":
                router = new BusinessRouter();
                break;
            case "safe"://安全服务
                router = new SafeRouter();
                break;
            default:
                break;
        }
        return router;
    }


    /**
     * 生成返回数据ResponseBean
     *
     * @param retCode 返回码
     * @param msgJson 返回数据json格式
     * @param tag     请求标识
     */
    private ResponseBean createResponseBean(int retCode, String msgJson, String tag) {
        ResponseBean responseBean = new ResponseBean();
        responseBean.setRetCode(retCode);
        responseBean.setMsgJson(msgJson);
        responseBean.setTag(tag);
        return responseBean;
    }

    /**
     * 错误返回
     *
     * @param errorCode 错误码
     * @param detailMsg 追加信息
     * @param tag       请求标识
     */
    private String fail(HZErrorCode errorCode, String detailMsg, String tag) {
        CommonErrorBean commonErrorBean = new CommonErrorBean(errorCode.getCode(), errorCode.getErrMessage() + "，" + detailMsg);
        ResponseBean responseBean = createResponseBean(0, new Gson().toJson(commonErrorBean), tag);
        return new Gson().toJson(responseBean);
    }

    private String fail(HZErrorCode errorCode, String tag) {
        CommonErrorBean commonErrorBean = new CommonErrorBean(errorCode);
        ResponseBean responseBean = createResponseBean(0, new Gson().toJson(commonErrorBean), tag);
        return new Gson().toJson(responseBean);
    }

    private String fail(String msgJson, String tag) {
        ResponseBean responseBean = createResponseBean(0, msgJson, tag);
        return new Gson().toJson(responseBean);
    }

    private String success(String msgJson, String tag) {
        ResponseBean responseBean = createResponseBean(1, msgJson, tag);
        return new Gson().toJson(responseBean);
    }

    /**
     * 回调返回错误结果
     *
     * @param errorCode 错误码
     * @param callback  回调方法
     * @param detailMsg 追加信息
     */
    private void callbackFail(final SafeAidlCallback callback, final HZErrorCode errorCode, final String detailMsg, final String tag) {
        if (callback != null) {
            //假设在子线程，需要获取主线程的Looper和Queue
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    //切到主线程执行，否则调用端收不到返回值
                    try {
                        callback.callback(fail(errorCode, detailMsg, tag));
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    /**
     * 回调返回错误结果
     *
     * @param errorCode 错误码
     * @param callback  回调方法
     */
    private void callbackFail(final SafeAidlCallback callback, final HZErrorCode errorCode, final String tag) {
        if (callback != null) {
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    //切到主线程执行，否则调用端收不到返回值
                    try {
                        callback.callback(fail(errorCode, tag));
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    /**
     * 回调返回错误结果
     *
     * @param msgJson  返回的json
     * @param callback 回调方法
     */
    private void callbackFail(final SafeAidlCallback callback, final String msgJson, final String tag) {
        if (callback != null) {
            //切到主线程执行，否则调用端收不到返回值
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    LogUtil.e("safeControl返回失败数据：" + fail(msgJson, tag));
                    try {
                        callback.callback(fail(msgJson, tag));
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    /**
     * 回调返回正确结果
     */
    public void callbackSuccess(final String msgJson, final SafeAidlCallback callback, final String tag) {
        if (callback != null) {
            //切到主线程执行，否则调用端收不到返回值
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    LogUtil.e("safeControl返回成功数据：" + success(msgJson, tag));
                    try {
                        callback.callback(success(msgJson, tag));
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    /**
     * 回调返回过程信息
     */
    public void callbackProgress(final String msgJson, final SafeAidlCallback callback, final String tag) {
        if (callback != null) {
            //切到主线程执行，否则调用端收不到返回值
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    ResponseBean responseBean = createResponseBean(2, msgJson, tag);
                    String s = new Gson().toJson(responseBean);
                    try {
                        callback.callback(s);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
}
